package ace.tool.generate.code.impl.service;

import ace.tool.generate.code.impl.manager.ui.UiManager;
import ace.tool.generate.code.impl.resolver.ui.model.bo.UiProjectContext;
import ace.tool.generate.code.impl.resolver.ui.resolver.UiProjectContextResolver;
import ace.tool.generate.code.impl.service.model.input.GenerateInput;
import com.fasterxml.jackson.databind.ObjectMapper;
import java.io.File;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import lombok.Builder;
import lombok.NoArgsConstructor;
import lombok.SneakyThrows;
import org.apache.commons.io.FileUtils;
import org.springframework.util.ResourceUtils;

/**
 * @author caspar
 * @date 2023/11/20 15:12
 */
@Builder
@NoArgsConstructor
public final class GeneratorUiProjectSchemaService {
  private final ObjectMapper objectMapper = new ObjectMapper();

  public void generate(List<GenerateInput> input) {
    boolean deleteFlag = false;
    for (GenerateInput generateInput : input) {
      UiProjectContext context = new UiProjectContextResolver(generateInput).resolve();
      if (!deleteFlag) {
        deleteFlag = true;
        this.deleteOldProject(context);
      }

      this.generateCoreDir(context);
    }
  }

  @SneakyThrows
  public void generate(String resourcePath) {
    File file = ResourceUtils.getFile(resourcePath);
    String fileContent = FileUtils.readFileToString(file, StandardCharsets.UTF_8);
    GenerateInput input = objectMapper.readValue(fileContent, GenerateInput.class);
    this.generate(Arrays.asList(input));
  }

  @SneakyThrows
  public void generateByFile(List<String> resourcePaths) {
    List<GenerateInput> inputs = new ArrayList<>();
    for (String resourcePath : resourcePaths) {
      File file = ResourceUtils.getFile(resourcePath);
      String fileContent = FileUtils.readFileToString(file, StandardCharsets.UTF_8);
      GenerateInput input = objectMapper.readValue(fileContent, GenerateInput.class);
      inputs.add(input);
    }

    this.generate(inputs);
  }

  private void generateCoreDir(UiProjectContext context) {
    new UiManager(context).generate();
  }

  @SneakyThrows
  private void deleteOldProject(UiProjectContext context) {

    File file = new File(context.getUiProjectInfo().getInfo().getRootDir());
    if (!file.exists()) {
      return;
    }
    FileUtils.forceDelete(file);
  }
}
